/**
 * Created by Freeman on 2016/7/25.
 */
import {ADD_TODO, DELETE_TODO, EDIT_TODO, COMPLETE_TODO, COMPLETE_ALL, CLEAR_COMPLETED} from '../constants/ActionTypes'
const initialState = [
    {
        text: 'Use Redux',
        completed: false,
        id: 0
    }
]
const todo = (state, action) => {
    switch (action.type) {
        case ADD_TODO:
            return {
                id: action.id,
                text: action.text,
                completed: false
            };
        case EDIT_TODO:
            if (state.id !== action.id) {
                return state
            }
            return {...state,text: action.text};
        case COMPLETE_TODO:
            return state.id === action.id?{...state,completed: !state.completed}:state;
        default:
            return state
    }
};

const todos = (state = initialState, action) => {
    switch (action.type) {
        case ADD_TODO:
            return [
                ...state,
                todo(undefined, {...action,id:state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1})
            ];
        case DELETE_TODO:
            return state.filter(t =>
                t.id !== action.id
            );
        case EDIT_TODO:
            return state.map(t =>
                todo(t,action)
            );
        case COMPLETE_TODO:
            return state.map(t =>
                todo(t, action)
        );
        case COMPLETE_ALL:
            const areAllMarked = state.every(todo =>todo.completed);
            return state.map(t =>
                Object.assign({}, t, {
                    completed: !areAllMarked
                })
            );
        case CLEAR_COMPLETED:
            return state.filter(t =>
                t.completed === false
            )
        default:
            return state
    }
};

export default todos;